/**
 * 数据迁移模块
 * 处理localStorage与服务器之间的数据同步
 */
class DataMigrationManager {
    constructor() {
        this.logger = window.logger ? window.logger.createContextLogger('DataMigration') : console;
        this.isMigrating = false;
        this.lastMigrationTime = null;
        this.migrationQueue = [];
        this.networkManager = window.networkManager;
        this.envConfig = window.envConfig;
        
        this._init();
    }
    
    /**
     * 初始化迁移管理器
     * @private
     */
    _init() {
        // 获取上次迁移时间
        this.lastMigrationTime = localStorage.getItem('lastMigrationTime') || null;
        
        // 监听网络状态变化
        if (this.networkManager) {
            this.networkManager.addListener(this._handleNetworkChange.bind(this));
        }
        
        this.logger.info('数据迁移管理器已初始化', { lastMigrationTime: this.lastMigrationTime });
    }
    
    /**
     * 处理网络状态变化
     * @private
     * @param {string} event - 事件类型
     * @param {Object} data - 事件数据
     */
    async _handleNetworkChange(event, data) {
        if (event === 'online' && data.isOnline) {
            this.logger.info('网络恢复，检查是否需要数据迁移');
            
            // 网络恢复时，先检查是否有待同步数据
            const hasPendingSync = await this._hasPendingSyncData();
            
            if (hasPendingSync) {
                this.logger.info('检测到离线期间有数据变更，开始同步');
                await this._syncOfflineChanges();
            } else {
                this.logger.info('没有待同步数据，执行常规数据迁移检查');
                // 没有待同步数据，执行常规数据迁移检查
                const result = await this.checkAndPerformMigration();
                if (result.status === 'success' && result.hasChanges) {
                    this.logger.info('网络恢复后数据迁移完成');
                }
            }
        } else if (event === 'offline') {
            this.logger.warn('网络连接已断开，数据将保存在本地');
            
            // 网络断开时，标记当前数据状态
            this._markOfflineDataState();
        }
    }
    
    /**
     * 检查并执行数据迁移
     * @returns {Promise<Object>} 迁移结果
     */
    async checkAndPerformMigration() {
        // 如果正在迁移中，不重复执行
        if (this.isMigrating) {
            this.logger.info('数据迁移正在进行中，跳过本次检查');
            return { status: 'skipped', reason: 'already_migrating' };
        }
        
        // 如果禁用了迁移功能，不执行
        if (this.envConfig && !this.envConfig.isMigrationEnabled()) {
            this.logger.info('数据迁移功能已禁用');
            return { status: 'skipped', reason: 'disabled' };
        }
        
        // 如果是离线模式，不执行
        if (this.envConfig && this.envConfig.isOfflineMode()) {
            this.logger.info('当前为离线模式，跳过数据迁移');
            return { status: 'skipped', reason: 'offline_mode' };
        }
        
        // 检查网络状态
        if (this.networkManager && !this.networkManager.getStatus().isOnline) {
            this.logger.info('网络不可用，跳过数据迁移');
            return { status: 'skipped', reason: 'offline' };
        }
        
        try {
            this.isMigrating = true;
            this.logger.info('开始数据迁移检查');
            
            // 检查API健康状态
            const isApiHealthy = await this._checkApiHealth();
            if (!isApiHealthy) {
                this.logger.warn('API不可用，跳过数据迁移');
                return { status: 'skipped', reason: 'api_unhealthy' };
            }
            
            // 执行迁移
            const migrationResult = await this._performMigration();
            
            // 更新迁移时间
            if (migrationResult.hasChanges) {
                this.lastMigrationTime = new Date().toISOString();
                localStorage.setItem('lastMigrationTime', this.lastMigrationTime);
                this.logger.info('数据迁移完成，更新迁移时间', { lastMigrationTime: this.lastMigrationTime });
            }
            
            return migrationResult;
        } catch (error) {
            this.logger.error('数据迁移失败:', error);
            return { status: 'error', error: error.message };
        } finally {
            this.isMigrating = false;
        }
    }
    
    /**
     * 检查API健康状态
     * @private
     * @returns {Promise<boolean>} API是否健康
     */
    async _checkApiHealth() {
        try {
            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
            const response = await fetch(`${baseUrl}/health`, {
                method: 'GET',
                cache: 'no-cache',
                timeout: 5000
            });
            
            return response.ok;
        } catch (error) {
            this.logger.error('API健康检查失败:', error);
            return false;
        }
    }
    
    /**
     * 执行实际的数据迁移
     * @private
     * @returns {Promise<Object>} 迁移结果
     */
    async _performMigration() {
        const result = {
            hasChanges: false,
            tasksMigrated: 0,
            notesMigrated: 0,
            settingsMigrated: 0
        };
        
        // 获取本地数据
        const localData = this._getLocalData();
        
        // 获取服务器数据
        const serverData = await this._getServerData();
        
        // 迁移任务
        const taskResult = await this._migrateTasks(localData.tasks, serverData.tasks);
        result.tasksMigrated = taskResult.count;
        result.hasChanges = result.hasChanges || taskResult.hasChanges;
        
        // 迁移笔记
        const noteResult = await this._migrateNotes(localData.notes, serverData.notes);
        result.notesMigrated = noteResult.count;
        result.hasChanges = result.hasChanges || noteResult.hasChanges;
        
        // 迁移设置
        const settingsResult = await this._migrateSettings(localData.settings, serverData.settings);
        result.settingsMigrated = settingsResult.count;
        result.hasChanges = result.hasChanges || settingsResult.hasChanges;
        
        this.logger.info('数据迁移完成', result);
        
        return result;
    }
    
    /**
     * 获取本地数据
     * @private
     * @returns {Object} 本地数据
     */
    _getLocalData() {
        try {
            return {
                tasks: JSON.parse(localStorage.getItem('tasks') || '[]'),
                notes: JSON.parse(localStorage.getItem('notes') || '[]'),
                settings: JSON.parse(localStorage.getItem('settings') || '{}')
            };
        } catch (error) {
            this.logger.error('获取本地数据失败:', error);
            return {
                tasks: [],
                notes: [],
                settings: {}
            };
        }
    }
    
    /**
     * 获取服务器数据
     * @private
     * @returns {Promise<Object>} 服务器数据
     */
    async _getServerData() {
        try {
            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
            
            const [tasksResponse, notesResponse, settingsResponse] = await Promise.all([
                fetch(`${baseUrl}/api/tasks`),
                fetch(`${baseUrl}/api/notes`),
                fetch(`${baseUrl}/api/settings`)
            ]);
            
            return {
                tasks: tasksResponse.ok ? await tasksResponse.json() : [],
                notes: notesResponse.ok ? await notesResponse.json() : [],
                settings: settingsResponse.ok ? await settingsResponse.json() : {}
            };
        } catch (error) {
            this.logger.error('获取服务器数据失败:', error);
            return {
                tasks: [],
                notes: [],
                settings: {}
            };
        }
    }
    
    /**
     * 迁移任务数据
     * @private
     * @param {Array} localTasks - 本地任务
     * @param {Array} serverTasks - 服务器任务
     * @returns {Promise<Object>} 迁移结果
     */
    async _migrateTasks(localTasks, serverTasks) {
        let count = 0;
        let hasChanges = false;
        
        // 创建服务器任务ID映射
        const serverTaskIds = new Set(serverTasks.map(task => task.id));
        
        // 筛选出需要迁移的任务
        const tasksToMigrate = localTasks.filter(task => {
            // 如果任务不在服务器上，需要迁移
            if (!serverTaskIds.has(task.id)) {
                return true;
            }
            
            // 如果任务更新时间晚于上次迁移时间，需要迁移
            if (this.lastMigrationTime && task.updatedAt) {
                const taskUpdatedAt = new Date(task.updatedAt);
                const lastMigration = new Date(this.lastMigrationTime);
                if (taskUpdatedAt > lastMigration) {
                    return true;
                }
            }
            
            return false;
        });
        
        // 迁移任务
        for (const task of tasksToMigrate) {
            try {
                const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                const response = await fetch(`${baseUrl}/api/tasks`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(task)
                });
                
                if (response.ok) {
                    count++;
                    hasChanges = true;
                    this.logger.debug('任务迁移成功:', task.id);
                } else {
                    this.logger.warn('任务迁移失败:', task.id, response.status);
                }
            } catch (error) {
                this.logger.error('任务迁移出错:', task.id, error);
            }
        }
        
        return { count, hasChanges };
    }
    
    /**
     * 迁移笔记数据
     * @private
     * @param {Array} localNotes - 本地笔记
     * @param {Array} serverNotes - 服务器笔记
     * @returns {Promise<Object>} 迁移结果
     */
    async _migrateNotes(localNotes, serverNotes) {
        let count = 0;
        let hasChanges = false;
        
        // 创建服务器笔记ID映射
        const serverNoteIds = new Set(serverNotes.map(note => note.id));
        
        // 筛选出需要迁移的笔记
        const notesToMigrate = localNotes.filter(note => {
            // 如果笔记不在服务器上，需要迁移
            if (!serverNoteIds.has(note.id)) {
                return true;
            }
            
            // 如果笔记更新时间晚于上次迁移时间，需要迁移
            if (this.lastMigrationTime && note.updatedAt) {
                const noteUpdatedAt = new Date(note.updatedAt);
                const lastMigration = new Date(this.lastMigrationTime);
                if (noteUpdatedAt > lastMigration) {
                    return true;
                }
            }
            
            return false;
        });
        
        // 迁移笔记
        for (const note of notesToMigrate) {
            try {
                const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                const response = await fetch(`${baseUrl}/api/notes`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(note)
                });
                
                if (response.ok) {
                    count++;
                    hasChanges = true;
                    this.logger.debug('笔记迁移成功:', note.id);
                } else {
                    this.logger.warn('笔记迁移失败:', note.id, response.status);
                }
            } catch (error) {
                this.logger.error('笔记迁移出错:', note.id, error);
            }
        }
        
        return { count, hasChanges };
    }
    
    /**
     * 迁移设置数据
     * @private
     * @param {Object} localSettings - 本地设置
     * @param {Object} serverSettings - 服务器设置
     * @returns {Promise<Object>} 迁移结果
     */
    async _migrateSettings(localSettings, serverSettings) {
        let count = 0;
        let hasChanges = false;
        
        // 比较设置差异
        const settingsToMigrate = {};
        
        for (const [key, value] of Object.entries(localSettings)) {
            if (serverSettings[key] !== value) {
                settingsToMigrate[key] = value;
            }
        }
        
        // 如果有设置需要迁移
        if (Object.keys(settingsToMigrate).length > 0) {
            try {
                const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                const response = await fetch(`${baseUrl}/api/settings`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(settingsToMigrate)
                });
                
                if (response.ok) {
                    count = Object.keys(settingsToMigrate).length;
                    hasChanges = true;
                    this.logger.debug('设置迁移成功:', settingsToMigrate);
                } else {
                    this.logger.warn('设置迁移失败:', response.status);
                }
            } catch (error) {
                this.logger.error('设置迁移出错:', error);
            }
        }
        
        return { count, hasChanges };
    }
    
    /**
     * 强制执行完整的数据迁移
     * @returns {Promise<Object>} 迁移结果
     */
    async forceFullMigration() {
        const logger = this.logger.createContextLogger('ForceMigration');
        
        try {
            logger.info('开始强制完整数据迁移');
            
            // 重置最后迁移时间，强制执行迁移
            this.lastMigrationTime = null;
            localStorage.setItem('lastMigrationTime', '0');
            
            // 执行迁移
            const result = await this.checkAndPerformMigration();
            
            logger.info('强制数据迁移完成', result);
            return result;
        } catch (error) {
            logger.error('强制数据迁移失败:', error);
            return {
                status: 'error',
                error: error.message,
                timestamp: new Date().toISOString()
            };
        }
    }
    
    /**
     * 检查是否有待同步的数据
     * @private
     * @returns {Promise<boolean>} 是否有待同步数据
     */
    async _hasPendingSyncData() {
        const logger = this.logger.createContextLogger('PendingSyncCheck');
        
        try {
            // 检查离线操作队列
            const offlineQueue = localStorage.getItem('offlineOperationQueue');
            if (offlineQueue) {
                const queue = JSON.parse(offlineQueue);
                if (queue.length > 0) {
                    logger.debug(`发现 ${queue.length} 个离线操作待同步`);
                    return true;
                }
            }
            
            // 检查数据变更标记
            const tasksChanged = localStorage.getItem('tasksChangedSinceLastSync') === 'true';
            const notesChanged = localStorage.getItem('notesChangedSinceLastSync') === 'true';
            const settingsChanged = localStorage.getItem('settingsChangedSinceLastSync') === 'true';
            
            if (tasksChanged || notesChanged || settingsChanged) {
                logger.debug(`数据变更标记: tasks=${tasksChanged}, notes=${notesChanged}, settings=${settingsChanged}`);
                return true;
            }
            
            // 检查本地数据是否比服务器数据新
            const lastSyncTime = localStorage.getItem('lastSyncTime');
            if (lastSyncTime) {
                const lastSync = new Date(lastSyncTime);
                const now = new Date();
                
                // 如果超过一定时间没有同步，可能需要检查
                const hoursSinceLastSync = (now - lastSync) / (1000 * 60 * 60);
                if (hoursSinceLastSync > 24) { // 超过24小时
                    logger.debug(`超过24小时未同步，需要检查数据一致性`);
                    return true;
                }
            }
            
            logger.debug('没有发现待同步数据');
            return false;
        } catch (error) {
            logger.error('检查待同步数据失败:', error);
            // 出错时默认认为有待同步数据，以确保数据安全
            return true;
        }
    }
    
    /**
     * 同步离线期间的数据变更
     * @private
     * @returns {Promise<Object>} 同步结果
     */
    async _syncOfflineChanges() {
        const logger = this.logger.createContextLogger('OfflineSync');
        
        try {
            logger.info('开始同步离线数据变更');
            
            const syncResults = {
                tasks: { success: 0, failed: 0 },
                notes: { success: 0, failed: 0 },
                settings: { success: 0, failed: 0 },
                operations: { success: 0, failed: 0 }
            };
            
            // 1. 处理离线操作队列
            await this._processOfflineOperationQueue(syncResults);
            
            // 2. 同步任务数据
            await this._syncTasksData(syncResults);
            
            // 3. 同步笔记数据
            await this._syncNotesData(syncResults);
            
            // 4. 同步设置数据
            await this._syncSettingsData(syncResults);
            
            // 5. 更新同步时间戳
            localStorage.setItem('lastSyncTime', new Date().toISOString());
            
            // 6. 清除变更标记
            localStorage.setItem('tasksChangedSinceLastSync', 'false');
            localStorage.setItem('notesChangedSinceLastSync', 'false');
            localStorage.setItem('settingsChangedSinceLastSync', 'false');
            
            // 计算总体结果
            const totalSuccess = syncResults.tasks.success + syncResults.notes.success + 
                               syncResults.settings.success + syncResults.operations.success;
            const totalFailed = syncResults.tasks.failed + syncResults.notes.failed + 
                              syncResults.settings.failed + syncResults.operations.failed;
            
            const result = {
                status: totalFailed === 0 ? 'success' : 'partial',
                syncResults,
                summary: {
                    totalSynced: totalSuccess,
                    totalFailed,
                    hasChanges: totalSuccess > 0
                },
                timestamp: new Date().toISOString()
            };
            
            logger.info('离线数据同步完成', result);
            return result;
        } catch (error) {
            logger.error('离线数据同步失败:', error);
            return {
                status: 'error',
                error: error.message,
                timestamp: new Date().toISOString()
            };
        }
    }
    
    /**
     * 处理离线操作队列
     * @private
     * @param {Object} syncResults - 同步结果对象
     */
    async _processOfflineOperationQueue(syncResults) {
        const logger = this.logger.createContextLogger('OperationQueue');
        
        try {
            const offlineQueue = localStorage.getItem('offlineOperationQueue');
            if (!offlineQueue) {
                logger.debug('没有离线操作队列');
                return;
            }
            
            const queue = JSON.parse(offlineQueue);
            if (queue.length === 0) {
                logger.debug('离线操作队列为空');
                return;
            }
            
            logger.info(`处理 ${queue.length} 个离线操作`);
            
            // 按时间戳排序操作
            queue.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
            
            // 处理每个操作
            const failedOperations = [];
            
            for (const operation of queue) {
                try {
                    await this._executeOfflineOperation(operation);
                    syncResults.operations.success++;
                    logger.debug(`操作成功: ${operation.type} ${operation.dataType} ${operation.id || ''}`);
                } catch (error) {
                    syncResults.operations.failed++;
                    logger.error(`操作失败: ${operation.type} ${operation.dataType} ${operation.id || ''}`, error);
                    
                    // 将失败的操作保存起来，以便后续重试
                    failedOperations.push({
                        ...operation,
                        failureReason: error.message,
                        retryCount: (operation.retryCount || 0) + 1
                    });
                }
            }
            
            // 保存失败的操作（如果有的话）
            if (failedOperations.length > 0) {
                localStorage.setItem('offlineOperationQueue', JSON.stringify(failedOperations));
                logger.warn(`${failedOperations.length} 个操作失败，已保存以便后续重试`);
            } else {
                localStorage.removeItem('offlineOperationQueue');
                logger.info('所有离线操作已成功处理');
            }
        } catch (error) {
            logger.error('处理离线操作队列失败:', error);
            throw error;
        }
    }
    
    /**
     * 执行单个离线操作
     * @private
     * @param {Object} operation - 操作对象
     */
    async _executeOfflineOperation(operation) {
        const { type, dataType, id, data } = operation;
        const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
        
        switch (type) {
            case 'create':
                if (dataType === 'tasks') {
                    const response = await fetch(`${baseUrl}/api/tasks`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    if (!response.ok) throw new Error(`创建任务失败: ${response.status}`);
                    return await response.json();
                } else if (dataType === 'notes') {
                    const response = await fetch(`${baseUrl}/api/notes`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    if (!response.ok) throw new Error(`创建笔记失败: ${response.status}`);
                    return await response.json();
                }
                break;
                
            case 'update':
                if (dataType === 'tasks') {
                    const response = await fetch(`${baseUrl}/api/tasks/${id}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    if (!response.ok) throw new Error(`更新任务失败: ${response.status}`);
                    return await response.json();
                } else if (dataType === 'notes') {
                    const response = await fetch(`${baseUrl}/api/notes/${id}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    if (!response.ok) throw new Error(`更新笔记失败: ${response.status}`);
                    return await response.json();
                } else if (dataType === 'settings') {
                    const response = await fetch(`${baseUrl}/api/settings`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    if (!response.ok) throw new Error(`更新设置失败: ${response.status}`);
                    return await response.json();
                }
                break;
                
            case 'delete':
                if (dataType === 'tasks') {
                    const response = await fetch(`${baseUrl}/api/tasks/${id}`, {
                        method: 'DELETE'
                    });
                    if (!response.ok) throw new Error(`删除任务失败: ${response.status}`);
                    return true;
                } else if (dataType === 'notes') {
                    const response = await fetch(`${baseUrl}/api/notes/${id}`, {
                        method: 'DELETE'
                    });
                    if (!response.ok) throw new Error(`删除笔记失败: ${response.status}`);
                    return true;
                }
                break;
                
            default:
                throw new Error(`未知的操作类型: ${type}`);
        }
        
        throw new Error(`无法执行操作: ${type} ${dataType}`);
    }
    
    /**
     * 同步任务数据
     * @private
     * @param {Object} syncResults - 同步结果对象
     */
    async _syncTasksData(syncResults) {
        const logger = this.logger.createContextLogger('TasksSync');
        
        try {
            // 检查本地任务是否有变更
            const tasksChanged = localStorage.getItem('tasksChangedSinceLastSync') === 'true';
            
            if (!tasksChanged) {
                logger.debug('任务数据无变更，跳过同步');
                return;
            }
            
            logger.info('开始同步任务数据');
            
            // 获取本地和服务器任务数据
            const localTasks = JSON.parse(localStorage.getItem('tasks') || '[]');
            const serverTasks = await this._getServerTasks();
            
            // 合并任务数据
            const mergedTasks = this._mergeTasksData(localTasks, serverTasks);
            
            // 更新本地数据
            localStorage.setItem('tasks', JSON.stringify(mergedTasks));
            
            // 将本地任务同步到服务器
            for (const task of mergedTasks) {
                try {
                    if (task.needsSync) {
                        if (task.id.startsWith('local_')) {
                            // 新创建的任务，添加到服务器
                            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                            const response = await fetch(`${baseUrl}/api/tasks`, {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(task)
                            });
                            if (response.ok) {
                                const serverTask = await response.json();
                                // 更新本地ID
                                this._updateLocalTaskId(task.id, serverTask.id);
                                syncResults.tasks.success++;
                            }
                        } else {
                            // 更新现有任务
                            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                            const response = await fetch(`${baseUrl}/api/tasks/${task.id}`, {
                                method: 'PUT',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(task)
                            });
                            if (response.ok) {
                                syncResults.tasks.success++;
                            }
                        }
                    }
                } catch (error) {
                    syncResults.tasks.failed++;
                    logger.error(`同步任务失败: ${task.id}`, error);
                }
            }
            
            logger.info('任务数据同步完成');
        } catch (error) {
            logger.error('同步任务数据失败:', error);
            syncResults.tasks.failed++;
        }
    }
    
    /**
     * 同步笔记数据
     * @private
     * @param {Object} syncResults - 同步结果对象
     */
    async _syncNotesData(syncResults) {
        const logger = this.logger.createContextLogger('NotesSync');
        
        try {
            // 检查本地笔记是否有变更
            const notesChanged = localStorage.getItem('notesChangedSinceLastSync') === 'true';
            
            if (!notesChanged) {
                logger.debug('笔记数据无变更，跳过同步');
                return;
            }
            
            logger.info('开始同步笔记数据');
            
            // 获取本地和服务器笔记数据
            const localNotes = JSON.parse(localStorage.getItem('notes') || '[]');
            const serverNotes = await this._getServerNotes();
            
            // 合并笔记数据
            const mergedNotes = this._mergeNotesData(localNotes, serverNotes);
            
            // 更新本地数据
            localStorage.setItem('notes', JSON.stringify(mergedNotes));
            
            // 将本地笔记同步到服务器
            for (const note of mergedNotes) {
                try {
                    if (note.needsSync) {
                        if (note.id.startsWith('local_')) {
                            // 新创建的笔记，添加到服务器
                            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                            const response = await fetch(`${baseUrl}/api/notes`, {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(note)
                            });
                            if (response.ok) {
                                const serverNote = await response.json();
                                // 更新本地ID
                                this._updateLocalNoteId(note.id, serverNote.id);
                                syncResults.notes.success++;
                            }
                        } else {
                            // 更新现有笔记
                            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                            const response = await fetch(`${baseUrl}/api/notes/${note.id}`, {
                                method: 'PUT',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(note)
                            });
                            if (response.ok) {
                                syncResults.notes.success++;
                            }
                        }
                    }
                } catch (error) {
                    syncResults.notes.failed++;
                    logger.error(`同步笔记失败: ${note.id}`, error);
                }
            }
            
            logger.info('笔记数据同步完成');
        } catch (error) {
            logger.error('同步笔记数据失败:', error);
            syncResults.notes.failed++;
        }
    }
    
    /**
     * 同步设置数据
     * @private
     * @param {Object} syncResults - 同步结果对象
     */
    async _syncSettingsData(syncResults) {
        const logger = this.logger.createContextLogger('SettingsSync');
        
        try {
            // 检查本地设置是否有变更
            const settingsChanged = localStorage.getItem('settingsChangedSinceLastSync') === 'true';
            
            if (!settingsChanged) {
                logger.debug('设置数据无变更，跳过同步');
                return;
            }
            
            logger.info('开始同步设置数据');
            
            // 获取本地设置
            const localSettings = JSON.parse(localStorage.getItem('settings') || '{}');
            
            // 同步设置到服务器
            try {
                const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
                const response = await fetch(`${baseUrl}/api/settings`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(localSettings)
                });
                if (response.ok) {
                    syncResults.settings.success++;
                    logger.info('设置数据同步成功');
                } else {
                    throw new Error(`设置同步失败: ${response.status}`);
                }
            } catch (error) {
                syncResults.settings.failed++;
                logger.error('同步设置数据失败:', error);
            }
        } catch (error) {
            logger.error('同步设置数据失败:', error);
            syncResults.settings.failed++;
        }
    }
    
    /**
     * 合并任务数据
     * @private
     * @param {Array} localTasks - 本地任务
     * @param {Array} serverTasks - 服务器任务
     * @returns {Array} 合并后的任务
     */
    _mergeTasksData(localTasks, serverTasks) {
        const mergedTasks = [];
        const taskMap = new Map();
        
        // 添加本地任务
        for (const task of localTasks) {
            taskMap.set(task.id, { ...task, source: 'local' });
        }
        
        // 添加服务器任务，如果存在冲突则以更新时间较晚的为准
        for (const task of serverTasks) {
            const existingTask = taskMap.get(task.id);
            if (!existingTask) {
                taskMap.set(task.id, { ...task, source: 'server' });
            } else {
                // 比较更新时间，使用较新的版本
                const localTime = new Date(existingTask.updatedAt || existingTask.createdAt);
                const serverTime = new Date(task.updatedAt || task.createdAt);
                
                if (serverTime > localTime) {
                    taskMap.set(task.id, { ...task, source: 'server', needsSync: false });
                } else {
                    // 本地版本较新，标记需要同步
                    taskMap.set(task.id, { ...existingTask, needsSync: true });
                }
            }
        }
        
        // 转换为数组并排序
        for (const task of taskMap.values()) {
            mergedTasks.push(task);
        }
        
        // 按创建时间排序
        mergedTasks.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
        
        return mergedTasks;
    }
    
    /**
     * 合并笔记数据
     * @private
     * @param {Array} localNotes - 本地笔记
     * @param {Array} serverNotes - 服务器笔记
     * @returns {Array} 合并后的笔记
     */
    _mergeNotesData(localNotes, serverNotes) {
        const mergedNotes = [];
        const noteMap = new Map();
        
        // 添加本地笔记
        for (const note of localNotes) {
            noteMap.set(note.id, { ...note, source: 'local' });
        }
        
        // 添加服务器笔记，如果存在冲突则以更新时间较晚的为准
        for (const note of serverNotes) {
            const existingNote = noteMap.get(note.id);
            if (!existingNote) {
                noteMap.set(note.id, { ...note, source: 'server' });
            } else {
                // 比较更新时间，使用较新的版本
                const localTime = new Date(existingNote.updatedAt || existingNote.createdAt);
                const serverTime = new Date(note.updatedAt || note.createdAt);
                
                if (serverTime > localTime) {
                    noteMap.set(note.id, { ...note, source: 'server', needsSync: false });
                } else {
                    // 本地版本较新，标记需要同步
                    noteMap.set(note.id, { ...existingNote, needsSync: true });
                }
            }
        }
        
        // 转换为数组并排序
        for (const note of noteMap.values()) {
            mergedNotes.push(note);
        }
        
        // 按创建时间排序
        mergedNotes.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
        
        return mergedNotes;
    }
    
    /**
     * 更新本地任务ID
     * @private
     * @param {string} localId - 本地ID
     * @param {string} serverId - 服务器ID
     */
    _updateLocalTaskId(localId, serverId) {
        try {
            const tasks = JSON.parse(localStorage.getItem('tasks') || '[]');
            
            for (let i = 0; i < tasks.length; i++) {
                if (tasks[i].id === localId) {
                    tasks[i].id = serverId;
                    tasks[i].needsSync = false;
                    break;
                }
            }
            
            localStorage.setItem('tasks', JSON.stringify(tasks));
            
            // 更新离线操作队列中的ID
            const offlineQueue = localStorage.getItem('offlineOperationQueue');
            if (offlineQueue) {
                const queue = JSON.parse(offlineQueue);
                for (const operation of queue) {
                    if (operation.dataType === 'tasks' && operation.id === localId) {
                        operation.id = serverId;
                    }
                }
                localStorage.setItem('offlineOperationQueue', JSON.stringify(queue));
            }
        } catch (error) {
            this.logger.error('更新本地任务ID失败:', error);
        }
    }
    
    /**
     * 更新本地笔记ID
     * @private
     * @param {string} localId - 本地ID
     * @param {string} serverId - 服务器ID
     */
    _updateLocalNoteId(localId, serverId) {
        try {
            const notes = JSON.parse(localStorage.getItem('notes') || '[]');
            
            for (let i = 0; i < notes.length; i++) {
                if (notes[i].id === localId) {
                    notes[i].id = serverId;
                    notes[i].needsSync = false;
                    break;
                }
            }
            
            localStorage.setItem('notes', JSON.stringify(notes));
            
            // 更新离线操作队列中的ID
            const offlineQueue = localStorage.getItem('offlineOperationQueue');
            if (offlineQueue) {
                const queue = JSON.parse(offlineQueue);
                for (const operation of queue) {
                    if (operation.dataType === 'notes' && operation.id === localId) {
                        operation.id = serverId;
                    }
                }
                localStorage.setItem('offlineOperationQueue', JSON.stringify(queue));
            }
        } catch (error) {
            this.logger.error('更新本地笔记ID失败:', error);
        }
    }
    
    /**
     * 标记离线数据状态
     * @private
     */
    _markOfflineDataState() {
        try {
            // 记录离线开始时间
            localStorage.setItem('offlineStartTime', new Date().toISOString());
            
            // 确保变更标记存在
            if (!localStorage.getItem('tasksChangedSinceLastSync')) {
                localStorage.setItem('tasksChangedSinceLastSync', 'false');
            }
            if (!localStorage.getItem('notesChangedSinceLastSync')) {
                localStorage.setItem('notesChangedSinceLastSync', 'false');
            }
            if (!localStorage.getItem('settingsChangedSinceLastSync')) {
                localStorage.setItem('settingsChangedSinceLastSync', 'false');
            }
            
            // 确保离线操作队列存在
            if (!localStorage.getItem('offlineOperationQueue')) {
                localStorage.setItem('offlineOperationQueue', JSON.stringify([]));
            }
            
            this.logger.info('离线数据状态已标记');
        } catch (error) {
            this.logger.error('标记离线数据状态失败:', error);
        }
    }
    
    /**
     * 获取服务器任务数据
     * @private
     * @returns {Promise<Array>} 服务器任务数据
     */
    async _getServerTasks() {
        try {
            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
            const response = await fetch(`${baseUrl}/api/tasks`);
            return response.ok ? await response.json() : [];
        } catch (error) {
            this.logger.error('获取服务器任务数据失败:', error);
            return [];
        }
    }
    
    /**
     * 获取服务器笔记数据
     * @private
     * @returns {Promise<Array>} 服务器笔记数据
     */
    async _getServerNotes() {
        try {
            const baseUrl = this.envConfig ? this.envConfig.getApiBaseUrl() : 'http://localhost:3000';
            const response = await fetch(`${baseUrl}/api/notes`);
            return response.ok ? await response.json() : [];
        } catch (error) {
            this.logger.error('获取服务器笔记数据失败:', error);
            return [];
        }
    }
    
    /**
     * 获取迁移状态
     * @returns {Object} 迁移状态
     */
    getStatus() {
        return {
            isMigrating: this.isMigrating,
            lastMigrationTime: this.lastMigrationTime,
            queueLength: this.migrationQueue.length
        };
    }
}

// 创建全局数据迁移管理器实例
const dataMigrationManager = new DataMigrationManager();

// 导出数据迁移管理器
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { dataMigrationManager, DataMigrationManager };
} else {
    window.dataMigrationManager = dataMigrationManager;
    window.DataMigrationManager = DataMigrationManager;
}